window.CKEDITOR_BASEPATH = '<?=_EDITOR_URL;?>';
window.CKFINDER_BASEPATH = '<?=_FILEMANAGER_URL;?>';

var pageLayout;

$(document).ready(function() {
	
	pageLayout = $('body').layout({ 
		
		defaults: {
			applyDefaultStyles: true,
			contentSelector: ".ui-layout-content",
			resizeContentWhileDragging: false,
			spacing_open: 4,
			spacing_closed: 4,
			closable: true,
			resizable: true,
			slidable: false,
			noRoomToOpenTip: "Недостаточно места",
			resizerTip: "Растянуть",
			maskIframesOnResize: true,
			togglerTip_open: "Закрыть",
			togglerTip_closed: "Открыть",
			onresize_end: resizePageElements,
			useStateCookie: true,
			cookie__name: 'splitter',
			cookie__path: '<?php echo Mozg::Router('http')->Create('module=admin'); ?>'
		},
		
		center: {
			findNestedContent: true,
			minWidth: 400
		},
		
		east: {
			findNestedContent: true,
			size: 260,
			spacing_closed:	0,
			togglerLength_open:	0				
		},
		
		west: {
			findNestedContent: true,
			size: 265,
			spacing_closed:	0,
			togglerLength_open:	0			
		},
		
		north: {
			closable: true,
			resizable: false,
			slidable: false,
			spacing_closed:	0,
			togglerLength_open:	0,
			spacing_open: 0
		},
		
		south: {
			closable: false,
			resizable: false,
			slidable: false,
			spacing_open: 0			
		}			
	});
	
	//fix bug in firefox with left pane
	pageLayout.resizeAll();	
	
	var closePanes = function(targets){
		$.each(targets.split(','), function(){
			if (pageLayout.state[this].isHidden) return;
			
			pageLayout.close("" + this);
			initPaneButtons(this);
		});		
		return false;		
	};

	var openPanes = function(targets){
		$.each(targets.split(','), function(){
			if (pageLayout.state[this].isHidden) return;
			
			pageLayout.open("" + this);
			initPaneButtons(this);
		});	
		return false;	
	};		
	
	var closePaneButtons = $('a.closePanes');
	closePaneButtons.click(function(){
		return closePanes(this.target);	
	});

	var openPaneButtons = $('a.openPanes');
	openPaneButtons.click(function(){
		return openPanes(this.target);	
	});	

	$('a.togglePanes').click(function(){
		var closed = true;
		$.each(this.target.split(','), function(){
			if (pageLayout.panes[this])
			{	
				closed = closed && pageLayout.state[this].isClosed;
			}			
		});	
		if (closed) openPanes(this.target);
		else closePanes(this.target);
		
		return false;
	});		
	
	var initPaneButtons = function(pane){
		var buttons = openPaneButtons.filter('[target='+pane+']');
		if (pageLayout.state[pane].isHidden)
		{
			buttons.hide();
		}	
		else if (pageLayout.state[pane].isClosed)
		{
			buttons.show();
		}
		else
		{
			buttons.hide();
		}	
	};
	
	//detect which panes should be opened
	$.each(['west', 'east'], function(){
		var html = pageLayout.panes[this].find('.ui-layout-content').html();
		if (!html)
		{	
			pageLayout.hide("" + this);
		}
		
		initPaneButtons(this);
	});	
	
	
	$('.ui-layout').css('visibility', 'visible');

	/******************************************************/
	
	$.ajaxSetup({
	  timeout: 30000,
	  cache: true
	});

	$('.loading').bind("ajaxSend", function(){
		   $(this).fadeIn();
		 }).bind("ajaxComplete", function(data){
		   $(this).fadeOut();
		 });	
	//-----------------------	

	$('a.icon').tipTip();	
	
	//-------------------
	$('a.del').live('click', function(){
		return confirmDelElement(this);
	});
	
	$('a.submit').live('click', function(){
		$(this).closest('form').submit();
		return false;
	});	

	//------menu---------
	var submenus = $('ul.level2');

	$('ul.top_menu li a').each(function(index){
		var obj = $(this);
		obj.index = index;
        obj.click(function () {

        	submenus.find('.fake').remove();
        	
			$('ul.top_menu li.active').removeClass('active');
			obj.parent('li').addClass('active');

			$('ul.level2:visible').hide();
			active_submenu = submenus.get(obj.index);
			if (!$(active_submenu).find('.active').size())
			{
	        	var subMenuActiveElem = submenus.find('li.active');
	        	if (subMenuActiveElem) 
	        	{
	        		title = $('ul.top_menu li.here a').html() + ' &gt; ' + subMenuActiveElem.find('a').html();
	        		var cloneSubElement = subMenuActiveElem.clone();
	        		cloneSubElement.addClass('active fake').find('a').html(title);
	        		$(active_submenu).append(cloneSubElement);
	        	}
			}	
			
			$(active_submenu).show();

			return false;
		});
	});
	
	//------------------------------------	

	$('.editor-container .icon-html').live('click', function(){
		return addEditorInstance($(this).attr('rel'));
	});
	
	//------------------------------------
	
	$.jGrowl.defaults.closerTemplate = '<div>скрыть все сообщения</div>';
	$.jGrowl.defaults.position = 'my-bottom-right';
	$.jGrowl.defaults.corners = 0;
	$.jGrowl.defaults.glue = 'before';

});

var activeTextAreaId;
function addEditorInstance(id)
{	
	if (!CKEDITOR) return false;
	CKEDITOR.timestamp = '<?php echo $this->Style()->GetStyleRevision('js'); ?>';
	
	var jObj = $('#'+id);
	if (!jObj) return false;	
	
	var mainCont = $('#ContentPane .ui-layout-content');
	var scrollTop = mainCont.get(0).scrollTop;
	var defaultZIndex = mainCont.css('z-index');
	
	mainCont.css('overflow', 'hidden').css('z-index', '666').find('.content').hide();
	var wrapper = $(document.createElement('div')).attr('id', 'wrapper_'+id);
	jObj.wrap(wrapper);
	mainCont.append(jObj);
	
	var editor = CKEDITOR.replace( id,
						{
							toolbar : 'basic'
						});
	
	editor.scrollTop = scrollTop;
	
	editor.on('focus', function(){
		activeTextAreaId = id;
	});

	editor.on('instanceReady', function( evt ) {
		resizePageElements();	
	});	

	editor.on('destroy', function( evt ) {
		$('#wrapper_'+id).replaceWith(jObj);
		mainCont.css('overflow', 'auto').css('z-index', defaultZIndex).find('.content').show();
		mainCont.get(0).scrollTop = evt.editor.scrollTop;
	});		
	
	return false;
}

function resizePageElements()
{
	var i;
	for (i in CKEDITOR.instances)
	{		
		var editor = CKEDITOR.instances[i];
		editor.resize( pageLayout.state.center.innerWidth, $('#ContentPane .ui-layout-content').innerHeight(), null, true);
	}		
}

function confirmDelElement(domElement)
{
	var elem = $(domElement);
	var title = elem.attr('title').length ? elem.attr('title') : elem.data('title');
	if (!title || !title.length) return true;
	if (confirm(title)) return true;
	return false;
}	

function insertAtCursor(myField, myValue) 
{
	//IE support
	if (document.selection) 
	{
		myField.focus();
		sel = document.selection.createRange();
		sel.text = myValue;
	}
	//MOZILLA/NETSCAPE support
	else if (myField.selectionStart || myField.selectionStart == '0') 
	{
		var startPos = myField.selectionStart;
		var endPos = myField.selectionEnd;
		myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
	} 
	else 
	{
		myField.value += myValue;
	}
}

/**********message handler***********/
function showMessage(message, is_error, is_static)
{
	params = {};
	if (is_error) params.theme = 'messageError';
	else params.theme = 'messageDone';

	if (is_static) params.sticky = true;

	$.jGrowl(message, params);
}

function showAllMessages(messages)
{
	var i, is_error, is_static;
	for (i in messages)
	{
		if (!messages[i].message) continue;
		
		if (messages[i].type == 1)
		{
			is_error = true;
			is_static = true;
		}
		else
		{
			is_error = false;
			is_static = false;			
		}	
		
		showMessage(messages[i].message, is_error, is_static);	
	}	
}

/****************ajax response handler******************/
function HandleResponseJSON(data, successCallback, errorCallback)
{
	showAllMessages(data.messages);
	
	if ((data.status == 0) && $.isFunction(successCallback))
	{
		successCallback(data.data);
	}
	else if ((data.status == 1) && $.isFunction(errorCallback))
	{
		errorCallback(data.data);
	}
	
	if (data.js)
	{
		$.globalEval(data.js);
	}	
}